import React, { useCallback, useEffect, useRef, useState } from 'react';
import Screenshot from './Screenshot';
import './index.less';
import { IImage } from './interface';
import testImage from './Battlecry.jpg'
export default () => {
    const [image, setImage] = useState<IImage | null>(null);
    const [curVideo, setCurVideo] = useState<File | null>(null);
    const videoRef = useRef<HTMLVideoElement>(null);
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files) {
            setCurVideo(e.target.files[0]);
        }
    };
    const onTimeUpdate = () => {
        draw();
    };
    const draw = useCallback(() => {
        if (!curVideo || !videoRef.current || !canvasRef.current) return;
        const ctx = canvasRef.current.getContext('2d');
        const { width, height } = canvasRef.current;
        ctx?.clearRect(0, 0, width, height);
        ctx?.drawImage(videoRef.current, 0, 0, width, height);
        const dataUrl = canvasRef.current.toDataURL();
        const $image = new Image();
        $image.src = dataUrl;
        $image.onload = function () {
            const data = {
                width,
                height,
                el: $image,
            };
            console.log(data);
            setImage(data);
        };
    }, [curVideo]);

    useEffect(() => {
        const $image = new Image();
        $image.src = testImage;
        $image.onload = function () {
            const data = {
                width: 480,
                height: 320,
                el: $image,
            };
            console.log(data);
            setImage(data);
        };
    }, []);

    useEffect(() => {
        if (!curVideo || !videoRef.current) return;
        const srcUrl = window.URL.createObjectURL(curVideo);
        videoRef.current.src = srcUrl;
        videoRef.current.load();
        videoRef.current.oncanplay = function () {
            draw();
        };
    }, [curVideo, draw]);

    return (
        <div>
            <Screenshot image={image} width={480} height={320} />
            <div className="flex-algin mt20">
                <input type="file" accept=".mp4" onChange={onFileChange} />
                <video ref={videoRef} width="480" height="320" onTimeUpdate={onTimeUpdate} muted controls />
                <canvas ref={canvasRef} width="480" height="320" />
            </div>
        </div>
    );
};
